// pages/detail/detail.js
import { getSongById, getLyricById } from '../../config/api'
let app = getApp()
Page({
  data: {
    songs: {}, // 歌曲信息
    duration: 0, // 歌曲的时长
    id: 0, // 歌曲id
    isPause: true, // 是否是暂停状态
    current: 0, // 当前歌曲播放进度
    isStopTime: false, // 判断是否拖拽进度条
    lyric: {}, // 歌词
    currentLyc: '', // 当前歌词进度
    list: {}, // 播放列表
    mode: 0, // 播放模式,默认[列表循环]
    modeText: ['列表循环','单曲循环','随机播放'] // 播放模式文字
  },
  onLoad: function (options) {
    this.animation = wx.createAnimation({
      'duration': '200',
      'timingFunction':'ease-out'
    })
    let { id } = options
    this.setData({
      id: id,
      list: app.globalData.playList
    })
    this.songsInfo(id)
    wx.getStorage({
      key: 'mode',
      success: (res => {
        this.setPlayTrack(res.data)
      }),
      fail: (res=>{
        this.setPlayTrack(this.data.mode)
      })
    })
  },
  songsInfo (id) {
    // 获取歌曲详情
    getSongById(id, res => {
      this.setData({
        songs: res.data.songs[0]
      })
      wx.setNavigationBarTitle({ // 设置标题文字
        title: res.data.songs[0].name,
      })
    })
    // 获取歌词
    getLyricById(id, res => {
      let obj = {}
      let { lyric } = res.data.lrc
      let reg = /\[(.*)?](.*)/g
      lyric.replace(reg, ($0, $1, $2) => {
        obj[$1.substring(0, 5)] = $2;
      })
      this.setData({
        lyric: obj
      })
    })
    // 歌曲播放
    let InnerAudioContext = app.globalData.songs
    if (!InnerAudioContext) {
      InnerAudioContext = app.globalData.songs = wx.createInnerAudioContext()
    }
    InnerAudioContext.src = `https://music.163.com/song/media/outer/url?id=${this.data.id}.mp3`
    InnerAudioContext.play()
    InnerAudioContext.onPlay(res => { })
    InnerAudioContext.onTimeUpdate(res => { //监听音频播放进度更新事件
      this.setData({
        duration: InnerAudioContext.duration
      })
      if (!this.data.isStopTime) {
        this.setData({
          current: InnerAudioContext.currentTime
        })
      }
      let { currentTime: c } = InnerAudioContext // 将currentTime 从InnerAudioContext解构出来重命名为 c
      let minute = Math.floor(c / 60)
      let seconds = Math.floor(c % 60)
      minute = minute < 10 ? '0' + minute : minute
      seconds = seconds < 10 ? '0' + seconds : seconds
      let currentLyc = minute + ':' + seconds
      if (currentLyc in this.data.lyric && ('el-' + currentLyc) !== this.data.currentLyc) {
        this.setData({
          currentLyc: 'el-' + currentLyc
        })
      }
    })
  },
  // 完成一次拖动后触发的事件
  changeSlider (e) {
    let { value } = e.detail
    this.setData({
      isStopTime: false,
      current: value
    })
    app.globalData.songs.seek(value)
  },
  // 拖动过程中触发的事件
  changingSlider(e){
    this.setData({
      isStopTime: true
    })
  },
  // 播放or暂停
  tapPlay () {
    let { songs } = app.globalData
    if (songs.paused) {
      songs.play()
      this.setData({
        isPause: true
      })
    } else {
      songs.pause()
      this.setData({
        isPause: false
      })
    }
  },
  // 显示歌曲列表
  showModel () {
    this.animation.height('100%')
                  .backgroundColor('rgba(0,0,0,0.5)').step()
    this.setData({ animation: this.animation.export() }) // export 方法每次调用后会清掉之前的动画操作
  },
  // 隐藏歌曲列表
  hideModel () {
    this.animation.backgroundColor('rgba(0,0,0,0)')
                  .height(0).step()
    this.setData({ animation: this.animation.export() })
  },
  // 切换歌曲
  toggleSong (e) {
    let { types } = e.currentTarget.dataset
    this.toggleSongCallback(false, types)
  },
  /*
  * 切换歌曲逻辑判断
  * isRandom 是否随机切换，true表示是，false表示否
  * types 值为prev或者next，prev表示上一首，next表示下一首
  */  
  toggleSongCallback(isRandom, types) {
    let { id, list } = this.data
    let i = list.findIndex(value => value.id === parseInt(id))
    if (isRandom) {
      i = Math.floor(Math.random() * list.length)
    } else {
      if (types === 'prev') { // 判断点击的是上一首（prev）还是下一首(next)
        if (i === 0){
          i = list.length
        }
        i--;
      } else {
        if (i === list.length - 1){
          i = -1
        }
        i++;
      }
    }
    this.setData({
      id: list[i].id
    })
    this.songsInfo(this.data.id)
  },
  // 点击弹出列表歌曲
  playListSong (e) {
    let {id} = e.currentTarget.dataset
    this.setData({
      id: id
    })
    this.songsInfo(id)
  },
  // 切换播放模式
  togggleMode (e) {
    let { mode } = e.currentTarget.dataset
    let { modeText } = this.data
    let InnerAudioContext = app.globalData.songs
    mode = parseInt(mode)
    if (mode === 0) {
      mode = mode + 1
      InnerAudioContext.loop = true;
    } else if (mode === 1){
      mode = mode + 1
      InnerAudioContext.loop = false;
    } else if (mode === 2){
      mode = 0
      InnerAudioContext.loop = false;
    }
    wx.setStorage({
      key: 'mode',
      data: mode,
    })
    this.setData({
      mode: mode
    })
    wx.showToast({
      title: modeText[mode],
      icon: 'none'
    })
  },
   // 设置播放顺序
  setPlayTrack(m) {
    let InnerAudioContext = app.globalData.songs
    this.setData({
      mode: m
    })
    if (this.data.mode === 1) {
      InnerAudioContext.loop = true;
    } else {
      InnerAudioContext.loop = false;
      InnerAudioContext.onEnded(res => { // 监听音频自然播放至结束的事件
        let { mode } = this.data
        if (mode === 0) { // 列表循环
          console.log('列表循环')
          this.toggleSongCallback(false, 'next')
        } else if (mode === 2) { // 随机播放
          this.toggleSongCallback(true)
          console.log('随机播放')
        }
      })
    }
  }
})